package com.jevons.geo_lib.geojson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jevons.geo_lib.geojson.adapter.GeoJsonAdapterFactory;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.Geometry;
import com.mapbox.geojson.GeometryAdapterFactory;


/**
 * Copyright 2020 JxGIS
 *
 * @file MapboxJsonHelper
 * @auth linaisheng
 * Created on 2022/7/13.
 * Description：
 */
public class MapboxJsonHelper {

    public static String featureCollectionToJson(FeatureCollection featureCollection) {
        GsonBuilder gson = new GsonBuilder();
        gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
        gson.registerTypeAdapterFactory(GeometryAdapterFactory.create());
        return gson.create().toJson(featureCollection);
    }

    public static String featureToJson(Feature feature) {
        Gson gson = new GsonBuilder()
                .registerTypeAdapterFactory(GeoJsonAdapterFactory.create())
                .registerTypeAdapterFactory(GeometryAdapterFactory.create())
                .create();


        // Empty properties -> should not appear in json string
        if (feature.properties().size() == 0) {
            feature = Feature.fromGeometry(feature.geometry(), null, feature.id(), feature.bbox());
        }

        return gson.toJson(feature);
    }

    public static String geometryToJson(Geometry geometry) {
        GsonBuilder gson = new GsonBuilder();
        gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
        return gson.create().toJson(geometry);
    }

}